/**
 *
 *
 * */
function MineToolbar() {
    var modelingBtn = $('#tempo-mine-model-btn');
    var viewingBtn = $('#tempo-mine-view-btn');
    var reportingBtn = $('#tempo-mine-report-btn');
    var publishBtn = $('#tempo-mine-publish-btn');

    var modelingPage = $('#tempo-mine-modeling');
    var viewingPage = $('#tempo-mine-viewing');
    var reportingPage = $('#tempo-mine-reporting');
    var publishPage = $('#tempo-mine-publish');
    var likeSubprocessNodess = ["loopsampledata", "subprocess", "clacrossvalidation", "regcrossvalidation", "bagging", "regressionBagging", "parameterselect"];
    /**
     * 是否加载过模型配置界面
     */
    var modelFirst = false;
    this.init = function () {
        bindEvent();
        var urlHash = window.location.hash;
        if (urlHash.indexOf("_") > -1) {
            var splitArr = urlHash.split("_");
            if (splitArr[1] == "modeling") {
                modelFirst = true;
            }
            Eventbus.trigger('selectButton.mine', splitArr[1]);
        } else {
            modelFirst = true;
            Eventbus.trigger('selectButton.mine', 'modeling');
        }
    }
    /**
     * 绑定工具条上按钮的事件
     */
    var bindEvent = function () {
        Eventbus.one('switchToModeling.mine', function () {
            //点击建模重新调整宽度
            $(".tempo-mine-board-headbar").find(".navigator-buttons").width(400);
            var modelTabCont = $(".tempo-mine-tab-curSelect").parent();
            modelTabCont.addClass("model-selected");
            //获取切换前是建模页面还是洞察页面
            var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
            var type = analyseStatus.getType();
            switchPage("modeling");
            Eventbus.trigger('refreshModelLogger.mine');
            //如果是洞察页面切换到建模页面，触发流程名称点击事件，退出到最外层流程
            if (type == "viewing") {
                $("#tempo-mine-designer").find(".navigator-path-text").trigger("click");
            }
        }, this);

        Eventbus.one('switchToViewing.mine', function (currentId) {
            var modelTabCont = $(".tempo-mine-tab-curSelect").parent();
            modelTabCont.removeClass("model-selected");
            switchPage("viewing");
            var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
            var currentId = currentId || analyseStatus.getMainId();
            if (currentId) {
                MineViewlingController(currentId);
                analyseStatus.setMainId(currentId); //设置当前加载的分析页
            }
        }, this);

        Eventbus.one('switchToPubling.mine', function () {
            switchPage("publish");
        }, this);

        Eventbus.one("refreshModelLogger.mine", function () {
            analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0]
            var id = analyseStatus.getMainId();
            if (id) {
                var page = analyseStatus.getFlowPanel(id);
                page.panel.flowpanel('showFlowLog');
            }
        });
        if (!window.apiPreview) {
            Eventbus.one("saveAnalyseFromBar.mine", mineSave, this);
            Eventbus.one("saveAnalyseFlow.mine", saveAnalyseFlow, this);
            Eventbus.one("startupFromBar.mine", mineRun, this);
            Eventbus.one("withcachestartupFromBar.mine", mineRunCache, this);
            Eventbus.one("stopFlowFromBar.mine", mineStop, this);
            Eventbus.one("refreshFromBar.mine", mineRefresh, this);
            Eventbus.bind("insightSettingAction1", insightSettingAction, this);
            Eventbus.bind("initinsight.mine", initinsight);
            Eventbus.one("saveAnalyseFlow", saveAnalyseFlow, this);
            Eventbus.one("mine.sheetClickAndChangeView", switchPage);
            //进行撤销操作
            Eventbus.bind("enableUndoButton.mineToolbar", enableUndoButton, this);
            //进行重做操作
            Eventbus.bind("enableRedoButton.mineToolbar", enableRedoButton, this);
            //更新撤销和重做按钮
            Eventbus.bind("enableUndoRedoButton.mineToolbar", enableUndoRedoMine, this);
            // 版本管理
            Eventbus.bind("versionSnapshot.mineToolbar", versionSnapshotAction, this);
            Eventbus.bind("versionSnapshotMore.mineToolbar", versionSnapshotMoreAction, this);
            Eventbus.bind("finishExcuteFlow.flowlogger", autoSaveVersionSnapshot, this);
        }
        //ctrl+z和ctrl+y
        $(document).unbind('keydown.undo').bind("keydown.undo", function (event) {
            var dialog = $('.tempo-dialog');
            var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
            var Type = analyseStatus.getType();
            var mainId = analyseStatus.getMainId();
            if (analyseStatus.getFlowPanel(mainId)) {
                var panel = analyseStatus.getFlowPanel(mainId).panel;
                var board = panel.flowpanel('getBoard');
                var isMove = board.miningboard("getSelectStatus");
                if (!isMove && event.ctrlKey && event.keyCode == 90) {
                    if ($(document).data("ui-widget-overlay")) {
                        return;
                    }
                    if (dialog.length > 0 || Type != 'modeling') {
                        return;
                    }
                    enableUndoButton();
                }
                if (!isMove && event.ctrlKey && event.keyCode == 89) {
                    if ($(document).data("ui-widget-overlay")) {
                        return;
                    }
                    if (dialog.length > 0 || Type != 'modeling') {
                        return;
                    }
                    enableRedoButton();
                }
            }
        });
    }
    var initinsight = function () {
        var insightTarget = $('#insight-setting-more-menu');
        if (!insightTarget.length) {
            insightTarget = $("<div tabindex='1'  style=' width: 120px;height: 180px;" +
                "position: absolute;left: 1615px;top: 78px;border: 1px solid #c0c0c0;" +
                "background: #fff;'id='insight-setting-more-menu'></div>").appendTo($("body"));
            var allSelect = $("<div  style='border-bottom: 1px solid #c0c0c0;height: 24px;padding-top: 5px;' >" +
                "<input type='checkbox' class='tempo-checkbox' id='allSelectBtn'><label for='allSelectBtn' style='margin-left: 10px' class='lableClass' id='lableAll'>&nbsp;全选</lable>" +
                "</div><div id='insightTotal' class='ui-icon tempo-ui-icon tempo-ui-icon-tip tempo-mine-button' style='margin-right: 44px;float: right;margin-top: -24px;'></div>");
            allSelect.appendTo(insightTarget);
            var insightOption = $("<div id='selectOption'>" +
                "<ul style='z-index:999;' id='insight-setting-ul-menu'>" +
                "<li><input type='checkbox' class='tempo-checkbox' id='dataCollection' checked='checked'><label for='dataCollection' class='lableClass' style='color: #3484C0' id='lableData'>&nbsp;数据集</lable></li>" +
                "<li><input type='checkbox' class='tempo-checkbox' id='nodeInsight'><label for='nodeInsight'class='lableClass' id='lableNode'>&nbsp;节点洞察</lable></li>" +
                "<li><input type='checkbox' class='tempo-checkbox' id='graphInsight' checked='checked'><label for='graphInsight'class='lableClass' id='lableGraph'>&nbsp;图表洞察</lable></li>" +
                "<li><input type='checkbox' class='tempo-checkbox' id='signalData' checked='checked'><label for='signalData'class='lableClass' id='lableSignal'>&nbsp;信号数据</lable></li>" +
                "</ul></div>");
            insightOption.appendTo(insightTarget);

            //增加提示框信息
            var helpInfo = "<div id='helpInfoInsight' style='background: rgb(243, 245, 247);" +
                "position:absolute;position:absolute;width:230px;height:90px;backgroud:#EAEDF1;" +
                "box-shadow:0px 0px 10px rgba(46,49,53,0.44);z-index:99999;text-align:left;padding: 2px'>" +
                "<div style='padding-left: 2px;padding-top: 5px'>" + TempoUtils.locale("mine.insight1") + "</div>" +
                "<div style='padding-left: 2px;padding-top: 5px'>" + TempoUtils.locale("mine.insight2") + "</div>" +
                "<div style='padding-left: 2px;padding-top: 5px'>" + TempoUtils.locale("mine.insight3") + "</div>" +
                "<div style='padding-left: 2px;padding-top: 5px'>" + TempoUtils.locale("mine.insight4") + "</div>" +
                "</div>";
            //判断只初始化一次
            if ($("#helpInfoInsight").length == 0) {
                $('body').append(helpInfo);
            }
            var x = $("#insightTotal").offset().left;
            var y = $("#insightTotal").offset().top;
            //适应屏幕分辨率
            var width = screen.width;
            if (width == 1920) {
                $("#helpInfoInsight").css("left", x + 5);
                $("#helpInfoInsight").css("top", y + 20);
            } else if (width == 1680) {
                $("#helpInfoInsight").css("left", x - 235);
                $("#helpInfoInsight").css("top", y + 20);
            } else if (width == 1600) {
                $("#helpInfoInsight").css("left", x - 315);
                $("#helpInfoInsight").css("top", y + 20);
            } else if (width == 1440 || width == 1400) {
                $("#helpInfoInsight").css("left", x - 475);
                $("#helpInfoInsight").css("top", y + 20);
            } else if (width == 1366) {
                $("#helpInfoInsight").css("left", x - 548);
                $("#helpInfoInsight").css("top", y + 20);
            } else if (width == 1280 || width == 1024 || width == 832 || width == 800) {
                $("#helpInfoInsight").css("left", x - 629);
                $("#helpInfoInsight").css("top", y + 20);
            } else {
                $("#helpInfoInsight").css("left", x + 10);
                $("#helpInfoInsight").css("top", y + 20);
            }
            $("#helpInfoInsight").hide();
            $("#insightTotal").mouseover(function () {
                $("#helpInfoInsight").show();
            })
            $("#insightTotal").mouseout(function () {
                $("#helpInfoInsight").hide();
            })
        }
        insightTarget.hide();
        backFillInsightControlCheckStatus(insightTarget)
    }


    /**
     * 洞察设置事件
     */
    var insightSettingAction = function (event, ele) {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var id = analyseStatus.getMainId();
        var page = analyseStatus.getFlowPanel(id);
        //判断是否在运行
        if (page.panel.flowpanel('isRunning')) {
            return;
        }
        //获取当前流程类型
        var flowType = Eventbus.triggerHandler("getFlowType.mine")[0];
        //洞察设置弹窗
        var insightTarget = $('#insight-setting-more-menu');
        if (!insightTarget.length) {
            insightTarget = $("<div tabindex='1'  style=' width: 120px;height: 180px;" +
                "position: absolute;left: 1615px;top: 78px;border: 1px solid #c0c0c0;" +
                "background: #fff;'id='insight-setting-more-menu'></div>").appendTo($("body"));
            var allSelect = $("<div style='border-bottom: 1px solid #c0c0c0;height: 24px;padding-top: 5px;' >" +
                "<input type='checkbox' class='tempo-checkbox' id='allSelectBtn'><label for='allSelectBtn' style='margin-left: 10px' class='lableClass' id='lableAll'>&nbsp;全选</lable>" +
                "</div><div id='insightTotal' class='ui-icon tempo-ui-icon tempo-ui-icon-tip tempo-mine-button' style='margin-right: 44px;float: right;margin-top: -24px;'></div>");
            allSelect.appendTo(insightTarget);
            var insightOption = $("<div id='selectOption'>" +
                "<ul style='z-index:999;' id='insight-setting-ul-menu'>" +
                "<li><input type='checkbox' class='tempo-checkbox' id='dataCollection' checked='checked'><label for='dataCollection' class='lableClass' style='color: #3484C0' id='lableData'>&nbsp;数据集</lable></li>" +
                "<li><input type='checkbox' class='tempo-checkbox' id='nodeInsight'><label for='nodeInsight'class='lableClass' id='lableNode'>&nbsp;节点洞察</lable></li>" +
                "<li><input type='checkbox' class='tempo-checkbox' id='graphInsight' checked='checked'><label for='graphInsight' class='lableClass' id='lableGraph'>&nbsp;图表洞察</lable></li>" +
                "<li><input type='checkbox' class='tempo-checkbox' id='signalData' checked='checked'><label for='signalData'class='lableClass' id='lableSignal'>&nbsp;信号数据</lable></li>" +
                "</ul></div>");
            insightOption.appendTo(insightTarget);

            //增加提示框信息
            var helpInfo = "<div id='helpInfoInsight' style='background: rgb(243, 245, 247);" +
                "position:absolute;position:absolute;width:300px;height:70px;backgroud:#EAEDF1;" +
                "box-shadow:0px 0px 10px rgba(46,49,53,0.44);z-index:99999;text-align:left;padding: 2px'>" +
                "<div style='padding-left: 2px;padding-top: 5px'>" + TempoUtils.locale("mine.insight1") + "</div>" +
                "<div style='padding-left: 2px;padding-top: 5px'>" + TempoUtils.locale("mine.insight2") + "</div>" +
                "<div style='padding-left: 2px;padding-top: 5px'>" + TempoUtils.locale("mine.insight3") + "</div>" +
                "<div style='padding-left: 2px;padding-top: 5px'>" + TempoUtils.locale("mine.insight4") + "</div>" +
                "</div>";
            //判断只初始化一次
            if ($("#helpInfoInsight").length == 0) {
                $('body').append(helpInfo);
            }
            var x = $("#insightTotal").offset().left;
            var y = $("#insightTotal").offset().top;
            //适应屏幕分辨率
            var width = screen.width;
            if (width == 1920) {
                $("#helpInfoInsight").css("left", x + 5);
                $("#helpInfoInsight").css("top", y + 20);
            } else if (width == 1680) {
                $("#helpInfoInsight").css("left", x - 235);
                $("#helpInfoInsight").css("top", y + 20);
            } else if (width == 1600) {
                $("#helpInfoInsight").css("left", x - 315);
                $("#helpInfoInsight").css("top", y + 20);
            } else if (width == 1440 || width == 1400) {
                $("#helpInfoInsight").css("left", x - 475);
                $("#helpInfoInsight").css("top", y + 20);
            } else if (width == 1366) {
                $("#helpInfoInsight").css("left", x - 548);
                $("#helpInfoInsight").css("top", y + 20);
            } else if (width == 1280 || width == 1024 || width == 832 || width == 800) {
                $("#helpInfoInsight").css("left", x - 629);
                $("#helpInfoInsight").css("top", y + 20);
            } else {
                $("#helpInfoInsight").css("left", x + 10);
                $("#helpInfoInsight").css("top", y + 20);
            }
            $("#helpInfoInsight").hide();
            $("#insightTotal").mouseover(function () {
                $("#helpInfoInsight").show();
            })
            $("#insightTotal").mouseout(function () {
                $("#helpInfoInsight").hide();
            })
        }
        //管道流程隐藏图标洞察和信号数据
        if ("plflow" == flowType) {
            //隐藏按钮
            insightTarget.find("#insight-setting-ul-menu").children().eq(2).css("display", "none");
            insightTarget.find("#insight-setting-ul-menu").children().eq(3).css("display", "none");
            //调整高度
            insightTarget.css("height", "100px");
            //隐藏提示信息
            $("#helpInfoInsight").children().eq(2).css("display", "none");
            $("#helpInfoInsight").children().eq(3).css("display", "none");
            //调整高度
            $("#helpInfoInsight").css("height", "48px");
        } else {
            //显示按钮
            insightTarget.find("#insight-setting-ul-menu").children().eq(2).css("display", "block");
            insightTarget.find("#insight-setting-ul-menu").children().eq(3).css("display", "block");
            //调整高度
            insightTarget.css("height", "180px");
            //显示提示信息
            $("#helpInfoInsight").children().eq(2).css("display", "block");
            $("#helpInfoInsight").children().eq(3).css("display", "block");
            //调整高度
            $("#helpInfoInsight").css("height", "90px");
        }
        //鼠标移出勾选框就将勾选数据进行保存
        insightTarget.unbind('mouseout').bind('mouseout', function () {
            var allInsightIsOpen = insightTarget.find("#allSelectBtn").is(":checked");
            var dataInsightIsOpen = insightTarget.find("#dataCollection").is(":checked");
            var nodeInsightIsOpen = insightTarget.find("#nodeInsight").is(":checked");
            var graphInsightIsOpen = insightTarget.find("#graphInsight").is(":checked");
            var signalDataInsightIsOpen = insightTarget.find("#signalData").is(":checked");
            var insightControlInfo = {};
            insightControlInfo.allInsightIsOpen = allInsightIsOpen;
            insightControlInfo.dataInsightIsOpen = dataInsightIsOpen;
            insightControlInfo.nodeInsightIsOpen = nodeInsightIsOpen;
            insightControlInfo.graphInsightIsOpen = graphInsightIsOpen;
            insightControlInfo.signalDataInsightIsOpen = signalDataInsightIsOpen;

            // 保存到数据库表中
            mineSave(null, null, false);
            // 保存到页面上
            var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
            var id = analyseStatus.getMainId();
            var page = analyseStatus.getFlowPanel(id);
            page.panel.flowpanel('updateInsightControlInfo', insightControlInfo);
        })
        //弹窗消失
        $(document).bind("click", function (e) {
            var target = $(e.target);
            if (target.closest("#insight-setting-more-menu,.tempo-icon-insight-setting,.tempo-icon-insight-setting-more").length == 0) {
                var allInsightIsOpen = insightTarget.find("#allSelectBtn").is(":checked");
                var dataInsightIsOpen = insightTarget.find("#dataCollection").is(":checked");
                var nodeInsightIsOpen = insightTarget.find("#nodeInsight").is(":checked");
                var graphInsightIsOpen = insightTarget.find("#graphInsight").is(":checked");
                var signalDataInsightIsOpen = insightTarget.find("#signalData").is(":checked");
                var insightControlInfo = {};
                insightControlInfo.allInsightIsOpen = allInsightIsOpen;
                insightControlInfo.dataInsightIsOpen = dataInsightIsOpen;
                insightControlInfo.nodeInsightIsOpen = nodeInsightIsOpen;
                insightControlInfo.graphInsightIsOpen = graphInsightIsOpen;
                insightControlInfo.signalDataInsightIsOpen = signalDataInsightIsOpen;

                // 保存到数据库表中
                mineSave(null, null, false);
                // 保存到页面上
                var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
                var id = analyseStatus.getMainId();
                var page = analyseStatus.getFlowPanel(id);
                page.panel.flowpanel('updateInsightControlInfo', insightControlInfo);
                insightTarget.hide();
                $(document).off('click');
            }
        });

        //复选框选中事件(全选)
        $('#insight-setting-more-menu').find("#allSelectBtn").change(function () {
            var flag = $('#insight-setting-more-menu').find("#allSelectBtn").is(":checked");
            if (flag) {
                insightTarget.find("input").attr("checked", "checked");
                insightTarget.find("input").prop("checked", true);
                insightTarget.find(".lableClass").css("color", "#3484C0");
            } else {
                insightTarget.find("input").removeAttr("checked", "checked");
                insightTarget.find("input").prop("checked", false);
                insightTarget.find(".lableClass").css("color", "black");
                $(".tempo-mining-tool-insight-button").addClass("ignore-insight");
            }
        })
        /**
         * 洞察设置复选框单选事件
         */
        $('#insight-setting-more-menu').find('#selectOption').find("input").change(function (e) {
            //属于信号分析分支下的节点  但是输出时D数据集的节点集合 用于取消数据集勾选时 放大镜关闭
            //后续信号节点  输出为数据集时  在此处进行添加节点id即可
            var signalAndDataSet = ["singalfeartureextact", "signalsimilarity", "signalchangepointdetection", "orderenvelope", "signalholographic2d", "signaltodata"];
            var insightControlInfo = {
                allInsightIsOpen: insightTarget.find("#allSelectBtn").is(":checked"),
                dataInsightIsOpen: insightTarget.find("#dataCollection").is(":checked"),
                nodeInsightIsOpen: insightTarget.find("#nodeInsight").is(":checked"),
                graphInsightIsOpen: insightTarget.find("#graphInsight").is(":checked"),
                signalDataInsightIsOpen: insightTarget.find("#signalData").is(":checked"),
            }
            // 保存到页面上
            var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
            var id = analyseStatus.getMainId();
            var page = analyseStatus.getFlowPanel(id);
            // 判断当前复选框是否被选中
            if (e.target.checked) {
                $(e.target).parent().find('label').css("color", "#3484C0");
                // 保存到数据库表中
                mineSave(null, null, false);
                page.panel.flowpanel('updateInsightControlInfo', insightControlInfo);
            } else {
                if (e.target.id == "dataCollection") {
                    $(e.target).parent().find('label').css("color", "#black");
                    //取消勾选数据集  放大镜图标事件触发
                    var insightIcon = $(".tempo-mining-tool-insight-button");
                    for (var i = 0; i < insightIcon.length; i++) {
                        //获取当前节点的数据
                        var nodeData = insightIcon.eq(i).parent().parent().parent().parent().miningnode('getData');
                        //去掉特征提取节点控制  由数据集控制
                        if (nodeData.type != window.constant.DATAMINE_SIGNAL || signalAndDataSet.indexOf(nodeData.nodeType) > -1) {
                            if (insightIcon.eq(i).hasClass('view-insight')) {
                                insightIcon.eq(i).trigger('click')
                            }
                        }

                    }
                }
                if (e.target.id == "signalData") {
                    $(e.target).parent().find('label').css("color", "#black");
                    //取消勾选数据集  放大镜图标事件触发
                    var insightIcon = $(".tempo-mining-tool-insight-button");
                    for (var i = 0; i < insightIcon.length; i++) {
                        //获取当前节点的数据
                        var nodeData = insightIcon.eq(i).parent().parent().parent().parent().miningnode('getData');
                        if (nodeData.type == window.constant.DATAMINE_SIGNAL && signalAndDataSet.indexOf(nodeData.nodeType) == -1) {
                            if (insightIcon.eq(i).hasClass('view-insight')) {
                                insightIcon.eq(i).trigger('click')
                            }
                        }

                    }
                }
                $(e.target).parent().find('label').css("color", "black");
                // 保存到数据库表中
                mineSave(null, null, false);
                // 保存到页面上
                page.panel.flowpanel('updateInsightControlInfo', insightControlInfo);
            }
            var checkArray = $('#insight-setting-ul-menu').find("input");
            // 定义是否全选状态，默认选中全选
            var falg = true;
            for (var i = 0; i < checkArray.length; i++) {
                if (!checkArray.eq(i).is(':checked')) {
                    falg = false;
                    break;
                }
            }
            // 全选的复选框
            var selectAllObj = $('#insight-setting-more-menu').find("#allSelectBtn");
            if (falg) {
                selectAllObj.attr("checked", "checked");
                selectAllObj.prop("checked", true);
                selectAllObj.parent().find('label').css("color", "#3484C0");
            } else {
                selectAllObj.removeAttr("checked", "checked");
                selectAllObj.prop("checked", false);
                selectAllObj.parent().find('label').css("color", "black");
            }
        })
        var offset = ele.offset();
        if (ele[0].className == "tempo-icon-insight-setting") {
            insightTarget.css("left", offset.left).css("top", offset.top + 30);
        } else {
            insightTarget.css("left", offset.left - 16).css("top", offset.top + 32);
        }
        insightTarget.show();
        insightTarget.focus();
        backFillInsightControlCheckStatus(insightTarget);
    }

    var backFillInsightControlCheckStatus = function (insightTarget) {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var id = analyseStatus.getMainId();
        var page = analyseStatus.getFlowPanel(id);
        var data = page.panel.flowpanel('getRootData');
        var insightControlInfos = {
            allInsightIsOpen: false,
            dataInsightIsOpen: true,
            graphInsightIsOpen: true,
            nodeInsightIsOpen: false,
            signalDataInsightIsOpen: true,
        }
        var insightControlInfo = {};
        if (data.insightControlInfo == undefined) {
            insightControlInfo = insightControlInfos;
        } else if (data.flow && data.flow.insightControlInfo) {
            insightControlInfo = data.flow.insightControlInfo || {};
        } else {
            insightControlInfo = data.insightControlInfo || {};
        }
        if (insightControlInfo.allInsightIsOpen) {
            insightTarget.find("#allSelectBtn").attr("checked", "checked");
            insightTarget.find("#lableAll").css("color", "#3484C0")
        } else {
            insightTarget.find("#allSelectBtn").removeAttr("checked", "checked");
            insightTarget.find("#lableAll").css("color", "black");
        }
        insightTarget.find("#allSelectBtn").prop("checked", insightControlInfo.allInsightIsOpen);
        if (insightControlInfo.dataInsightIsOpen) {
            insightTarget.find("#lableData").css("color", "#3484C0")
            insightTarget.find("#dataCollection").attr("checked", "checked");
        } else {
            insightTarget.find("#dataCollection").removeAttr("checked", "checked");
            insightTarget.find("#lableData").css("color", "black");
        }
        insightTarget.find("#dataCollection").prop("checked", insightControlInfo.dataInsightIsOpen);
        if (insightControlInfo.nodeInsightIsOpen) {
            insightTarget.find("#lableNode").css("color", "#3484C0")
            insightTarget.find("#nodeInsight").attr("checked", "checked");
        } else {
            insightTarget.find("#nodeInsight").removeAttr("checked", "checked");
            insightTarget.find("#lableNode").css("color", "black");
        }
        insightTarget.find("#nodeInsight").prop("checked", insightControlInfo.nodeInsightIsOpen);
        if (insightControlInfo.graphInsightIsOpen) {
            insightTarget.find("#lableGraph").css("color", "#3484C0")
            insightTarget.find("#graphInsight").attr("checked", "checked");
        } else {
            insightTarget.find("#graphInsight").removeAttr("checked", "checked");
            insightTarget.find("#lableGraph").css("color", "black");
        }
        insightTarget.find("#graphInsight").prop("checked", insightControlInfo.graphInsightIsOpen);
        if (insightControlInfo.signalDataInsightIsOpen) {
            insightTarget.find("#lableSignal").css("color", "#3484C0")
            insightTarget.find("#signalData").attr("checked", "checked");
        } else {
            insightTarget.find("#signalData").removeAttr("checked", "checked");
            insightTarget.find("#lableSignal").css("color", "black");
        }
        insightTarget.find("#signalData").prop("checked", insightControlInfo.signalDataInsightIsOpen);
    }

    var getInsightControlInfo = function () {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var id = analyseStatus.getMainId();
        var page = analyseStatus.getFlowPanel(id);
        var data = page.panel.flowpanel('getRootData');
        var insightControlInfo = data.insightControlInfo;
        return insightControlInfo;
    }

    var autoSaveVersionSnapshot = function (result, flowId) {
        if (flowId) {
            var page = analyseStatus.getFlowPanel(flowId);
            var data = page.panel.flowpanel('getRootData');
            // 去除重复的flowReadyData(与flow重复)
            delete data.flowReadyData
            var analyseId = window[constant.ANALYSE_ID];
            var content = TempoMineUtils.encodeParams(JSON.stringify(data));
            $.post(contextPath + '/api/ai/snapshot/auto-save', {
                analyseId: analyseId,
                flowId: flowId,
                content: content
            }, function (d) {
            });
        }
    }
    /**
     * 版本管理
     * @param event
     * @param ele
     */
    var versionSnapshotAction = function (event, ele) {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var id = analyseStatus.getMainId();
        var page = analyseStatus.getFlowPanel(id);
        if (page.panel.flowpanel('isRunning')) {
            return;
        }
        var data = page.panel.flowpanel('getRootData');
        // 去除重复的flowReadyData(与flow重复)
        delete data.flowReadyData
        var analyseId = window[constant.ANALYSE_ID];
        var url = contextPath + '/api/ai/snapshot/view/add';
        var param = {
            analyseId: analyseId,
            resourceId: id,
            content: TempoMineUtils.encodeParams(JSON.stringify(data))
        };
        var target = "tempo-mine-snapshot-add-config-panel";
        $m.loadHtml(url, $("body"), target, param);
    };
    var versionManageAction = function (event, ele) {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var analyseId = window[constant.ANALYSE_ID];
        var id = analyseStatus.getMainId();
        var page = analyseStatus.getFlowPanel(id);
        if (page.panel.flowpanel('isRunning')) {
            return;
        }
        var url = contextPath + '/api/ai/snapshot/view/index';
        var param = {
            analyseId: analyseId,
            resourceId: id
        };
        var target = "tempo-mine-snapshot-manage-config-panel";
        $m.loadHtml(url, $("body"), target, param);
    };
    var versionSnapshotMoreAction = function (event, ele) {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var analyseId = window[constant.ANALYSE_ID];
        var id = analyseStatus.getMainId();
        var page = analyseStatus.getFlowPanel(id);
        if (page.panel.flowpanel('isRunning')) {
            return;
        }
        var target = $('#version-snapshot-more-menu');
        if (!target.length) {
            target = $("<ul style='z-index:999;' id='version-snapshot-more-menu'></ul>").appendTo($("body")).contextmenu({
                data: [{
                    text: '保存版本',
                    icon: "ui-icon tempo-ui-icon tempo-ui-icon-snapshot-make",
                    id: '_to_make_snapshot'
                }, {
                    text: '管理版本',
                    icon: "ui-icon tempo-ui-icon tempo-ui-icon-snapshot-rollback",
                    id: '_to_manage_snapshot',
                }],
                select: function (e1, ui) {
                    var selectedId = ui.select.id;
                    if ("_to_make_snapshot" == selectedId) {
                        versionSnapshotAction();
                        return;
                    }
                    if ("_to_manage_snapshot" == selectedId) {
                        versionManageAction();
                        return;
                    }
                }
            });
        }
        var offset = ele.offset();
        target.contextmenu("show", {position: {left: offset.left - 30, top: offset.top + 30, width: 100}});
    };
    /**
     * 进行撤销操作
     */
    var enableUndoButton = function () {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var id = analyseStatus.getMainId();
        var undoManager = analyseStatus.getUndoManager();
        var panel = analyseStatus.getFlowPanel(id);
        var board = panel.panel.flowpanel('getBoard');
        var disabled = $('#' + $(board).attr('flow-panel')).flowpanel('isRunning');
        var isStop = !(panel.panel.find('.tempo-mine-stop').hasClass('button-disabled'));
        if ((disabled && !isStop) || (isStop)) {
            return;
        }
        if (undoManager.hasUndo()) {
            //还能够撤销，撤销应为黑色
            undoManager.undo();
            //Eventbus.trigger("enableUndoButton.mineToolbar",true);
            panel.panel.find('.tempo-mine-toolbar-undo-button').removeClass("tempo-ui-icon-undo-dis").addClass("tempo-ui-icon-undo").addClass("tempo-mine-toolbar-undoandredo-button-show");
        }
        if (!undoManager.hasUndo()) {
            //无法撤销，撤销应为灰色
            //Eventbus.trigger("enableUndoButton.mineToolbar",false);
            panel.panel.find('.tempo-mine-toolbar-undo-button').removeClass("tempo-ui-icon-undo").addClass("tempo-ui-icon-undo-dis").removeClass("tempo-mine-toolbar-undoandredo-button-show");
        }
        enableUndoRedoMine();
    }

    /**
     * 进行重做操作
     */
    var enableRedoButton = function () {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var id = analyseStatus.getMainId();
        var undoManager = analyseStatus.getUndoManager();
        var panel = analyseStatus.getFlowPanel(id);
        var board = panel.panel.flowpanel('getBoard');
        var disabled = $('#' + $(board).attr('flow-panel')).flowpanel('isRunning');
        var isStop = !(panel.panel.find('.tempo-mine-stop').hasClass('button-disabled'));
        if ((disabled && !isStop) || (isStop)) {
            return;
        }
        if (undoManager.hasRedo()) {
            undoManager.redo();
            //Eventbus.trigger("enableRedoButton.mineToolbar",true);
            panel.panel.find('.tempo-mine-toolbar-redo-button').removeClass('tempo-ui-icon-redo-dis').addClass("tempo-ui-icon-redo").addClass("tempo-mine-toolbar-undoandredo-button-show");
        }
        if (!undoManager.hasRedo()) {
            //Eventbus.trigger("enableRedoButton.mineToolbar",false);
            panel.panel.find('.tempo-mine-toolbar-redo-button').removeClass('tempo-ui-icon-redo').addClass("tempo-ui-icon-redo-dis").removeClass("tempo-mine-toolbar-undoandredo-button-show");
        }
        enableUndoRedoMine();
    }

    /**
     * 撤销显示
     */
    var enableUndoMine = function (flag, panel) {
        if (flag) {
            panel.panel.find('.tempo-mine-toolbar-undo-button').removeClass("tempo-ui-icon-undo-dis").addClass("tempo-ui-icon-undo").addClass("tempo-mine-toolbar-undoandredo-button-show");
        } else {
            panel.panel.find('.tempo-mine-toolbar-undo-button').removeClass("tempo-ui-icon-undo").addClass("tempo-ui-icon-undo-dis").removeClass("tempo-mine-toolbar-undoandredo-button-show");
        }
    }

    /**
     * 重做显示
     */
    var enableRedoMine = function (flag, panel) {
        if (flag) {
            panel.panel.find('.tempo-mine-toolbar-redo-button').removeClass('tempo-ui-icon-redo-dis').addClass("tempo-ui-icon-redo").addClass("tempo-mine-toolbar-undoandredo-button-show");
        } else {
            panel.panel.find('.tempo-mine-toolbar-redo-button').removeClass('tempo-ui-icon-redo').addClass("tempo-ui-icon-redo-dis").removeClass("tempo-mine-toolbar-undoandredo-button-show");
        }
    }

    /**
     * 更新撤销和重做显示
     */
    var enableUndoRedoMine = function () {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var id = analyseStatus.getMainId();
        var undoManager = analyseStatus.getUndoManager();
        var panel = analyseStatus.getFlowPanel(id);
        //洞察页面是没有panel的
        if (panel == undefined) {
            return;
        }
        var board = panel.panel.flowpanel('getBoard');
        var disabled = $('#' + $(board).attr('flow-panel')).flowpanel('isRunning');
        var isStop = !(panel.panel.find('.tempo-mine-stop').hasClass('button-disabled'));
        if ((disabled && !isStop) || (isStop)) {
            return;
        }
        if (undoManager.hasUndo()) {
            enableUndoMine(true, panel);
        } else {
            enableUndoMine(false, panel);
        }
        if (undoManager.hasRedo()) {
            enableRedoMine(true, panel);
        } else {
            enableRedoMine(false, panel);
        }
    }

    /**
     * 更新回退按钮状态
     */
    var updateUndoBtnState = function () {
        Eventbus.trigger('enableUndoRedoButton.mineToolbar');
    }
    /*切换面板*/
    var switchPage = (function (type) {
        var viewStack = [{
            name: 'modeling',
            page: modelingPage,
            button: modelingBtn,
            layout: {
                scrollToBookmarkOnLoad: false,
                panes: {
                    enableCursorHotkey: false,
                },
                west: {
                    resizable: false,
                    size: 230,
                    spacing_open: 5
                },
                center: {
                    onresize_end: function () {
                        //调整页面大小时调整节点位置
                        //board.miningboard("updateSize");
                    }
                }
            },
            render: function () {
                $("#tempo-mine-list").tabs();
            }
        }, {
            name: 'viewing',
            page: viewingPage,
            button: viewingBtn,
            layout: {
                north: {
                    resizable: false,
                    size: 280,
                    spacing_open: 0
                },
                center: {
                    onresize_end: function () {
                        Eventbus.trigger('viewingResize.mine');
                    }
                },
                //去掉页面热键
                panes: {
                    enableCursorHotkey: false,
                },
            }
        }, {
            name: 'publish',
            page: publishPage,
            button: publishBtn,
            layout: {
                panes: {
                    enableCursorHotkey: false,
                },
                west: {
                    resizable: false,
                    size: 70,
                    spacing_open: 0
                },
                center: {}
            }
        }, {
            name: 'reporting',
            page: reportingPage,
            button: reportingBtn,
            layout: {
                panes: {
                    enableCursorHotkey: false,
                },
                west: {
                    resizable: false,
                    size: 230,
                    spacing_open: 1
                },
                center: {}
            }
        }];
        /**
         * 当前只显示一个面板
         */
        var switchOne = function (name) {
            /*var urlHash = window.location.hash;
            if (urlHash.indexOf("_") > -1) {
                var splitArr = urlHash.split("_");
                window.location.hash = splitArr[0] + "_" + name;
            } else if (urlHash && urlHash.length > 0) {
                window.location.hash = urlHash + "_" + name;
            }*/
            //处理安全扫描问题Cross-Site Scripting: DOM
            var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
            var flowId = analyseStatus.getMainId();
            if (flowId) {
                window.location.hash = "#" + flowId + "_" + name;
            }
            //@bug修改数组的循环方式，foreach可能会导致页面切换出错(点击模型读取后，再切换)
            viewStack.forEach(function (ele, i) {
                if (ele.name == name) {
                    ele.page.show();
                    if (!ele.page.attr('_tempo-container')) {
                        ele.page.layout(ele.layout);
                        ele.page.attr('_tempo-container', '1');
                        var render = ele.render || function () {
                        };
                        render();
                    }
                    if (name == "reporting") {
                        $('#tempo-mine-model-view-container').hide();
                    } else {
                        $('#tempo-mine-model-view-container').show();
                        if (name == "publish") {
                            ele.page.find('#publish-mine-layout').show().layout({
                                west: {
                                    resizable: false,
                                    size: '40%',
                                    closable: false,
                                    spacing_open: 5
                                }
                            });
                            new MinePublishController();
                        }
                    }
                } else {
                    ele.page.hide();
                }
            });
            if ($("#tempo-mine-alg-config-page-id")) {
                $("#tempo-mine-alg-config-page-id").html("");
            }
        }
        var loader = {
            modeling: function (boardId) {
                $('#tempo-mine-element-library-option').unbind("click").bind("click", function () {
                    //对要素库进行渲染
                    Eventbus.trigger("loadMineElementLibrary.mine");
                    if (!$(this).hasClass('tempo-mine-library-manager-option-select')) {
                        $(this).addClass('tempo-mine-library-manager-option-select');
                    }
                    $(this).siblings().removeClass('tempo-mine-library-manager-option-select');
                }).attr("title", TempoUtils.locale("mine.yaosukutitle"));

                var modelTitle = TempoUtils.locale("mine.moxingkutitle");

                $('#tempo-mine-model-library-option').unbind("click").bind("click", function () {
                    Eventbus.trigger("loadMineModelLibrary.mine");
                    if (!$(this).hasClass('tempo-mine-library-manager-option-select')) {
                        $(this).addClass('tempo-mine-library-manager-option-select');
                    }
                    $(this).siblings().removeClass('tempo-mine-library-manager-option-select');
                }).attr("title", modelTitle).html(modelTitle);

                $('#tempo-mine-element-library-option').trigger('click');
                var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
                var id = analyseStatus.getMainId();
                if (id && boardId == id && "modeling" != analyseStatus.getType()) {
                    var page = analyseStatus.getFlowPanel(id);
                    page && page.panel && page.panel.show();
                    var flowId = "#fc-" + TempoMineUtils.analyseStatus.getMainId();
                    var selectPercent = $(flowId).find(".navigator-buttons").find(".tempo-mine-designer-mode").length;
                    var startNodeOutrDiv = $(flowId).find("#mine-start-node-outer-div").length;
                    if (selectPercent > 0 && startNodeOutrDiv == 0) {
                        $(".parameterselect-parameters").find("#parameterselect-btn-config").hide();
                        $(".bagging-parameters").find("#bagging-parameters-btn").hide();
                        $(".regressionBagging-parameters").find("#regressionBagging-parameters-btn").hide();
                    }
                }
            },
            viewing: function (boardId) {
                //隐藏切换到洞察界面前设计器
                var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
                var id = analyseStatus.getMainId();
                if (id) {
                    var page = analyseStatus.getFlowPanel(id);
                    page && page.panel && page.panel.hide();
                }
            },
            reporting: function () {

            },
            publish: function () {

            }
        };

        return function (type) {
            //tempo-mine-model-tabs，切换页签的总体容器
            var modelTabs = $('#tempo-mine-model-tabs');
            if (type == 'publish') {
                $("#tempo-mine-model-view-container").layout().hide('south');
            } else {
                $("#tempo-mine-model-view-container").layout().show('south');
            }

            //.tempo-story-tab-cont,切换叶签的div
            var modelTabCont = modelTabs.find('.tempo-mine-tab-cont');
            var boardId = modelTabCont.find("span.tempo-mine-tab-curSelect").attr("linkid");
            if (window.apiDesigner) {
                //boardId = window[constant.ANALYSE_ID];
            }
            var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
            switchOne(type);
            loader[type](boardId);
            analyseStatus.setType(type);
            //boardId只能在loadBorad的时候进行设置，不能在其它地方设置，否则会引页面错乱
            var panel = analyseStatus.getFlowPanel(boardId);
            //当发现当前iD对应的panel为空，则说明没有加载设计器，触发加载事件
            if (!panel && type == 'modeling') {
                Eventbus.trigger("mining_board_load.mine", boardId);
            }
            if (window.apiPreview) {
                modelingPage.layout().hide('west');
            }
        }
    })();
    /**
     * 保存，包括挖掘流、洞察资源库、报告等等
     * 可以指定保存的流程
     * @param e: 保存按钮触发
     * @param analyseId： 保存的分析主题ID
     */
    var mineSave = function (e, analyseId, isRunAfter) {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var id = analyseId || analyseStatus.getMainId();
        var page = analyseStatus.getFlowPanel(id);
        // 保存按钮置灰，则不触发保存事件
        if (!page.panel.find('.tempo-mine-save.tempo-ui-blue').length && !isRunAfter) {
            return;
        }
        var data = page.panel.flowpanel('getRootData');
        var insightControlInfos = {
            allInsightIsOpen: false,
            dataInsightIsOpen: true,
            graphInsightIsOpen: true,
            nodeInsightIsOpen: false,
            signalDataInsightIsOpen: true,
        }
        var insightControlInfo = {};
        if (data.insightControlInfo == undefined) {
            insightControlInfo = insightControlInfos;
        } else {
            var insightTarget = $('#insight-setting-more-menu');
            var allInsightIsOpen = insightTarget.find("#allSelectBtn").is(":checked");
            var dataInsightIsOpen = insightTarget.find("#dataCollection").is(":checked");
            var nodeInsightIsOpen = insightTarget.find("#nodeInsight").is(":checked");
            var graphInsightIsOpen = insightTarget.find("#graphInsight").is(":checked");
            var signalDataInsightIsOpen = insightTarget.find("#signalData").is(":checked");
            insightControlInfo.allInsightIsOpen = allInsightIsOpen;
            insightControlInfo.dataInsightIsOpen = dataInsightIsOpen;
            insightControlInfo.nodeInsightIsOpen = nodeInsightIsOpen;
            insightControlInfo.graphInsightIsOpen = graphInsightIsOpen;
            insightControlInfo.signalDataInsightIsOpen = signalDataInsightIsOpen;
        }
        data.insightControlInfo = insightControlInfo;
        // 去除重复的flowReadyData(与flow重复)
        delete data.flowReadyData
        if (isRunAfter && isRunAfter == true) {
            //只有提交运行后再把节点信息恢复时tempoSubFullInfo的才是准确的 其他情况tempoSubFullInfo可能不是最新的，导致改动部分被覆盖
            subprocessAdd(data);
        }
        var pro = null;
        if (e) {
            pro = Mask.create();
        }
        //只有当importNotExecuted为true时才修改导入未执行的状态为false
        if (data && data.importNotExecuted) {
            data.importNotExecuted = false;
            page.panel.flowpanel('updateImportNotExecuted', data.importNotExecuted);
        }
        $.ajax({
            url: contextPath + '/api/ai/resource/save',
            data: {
                id: id,
                content: TempoMineUtils.encodeParams(JSON.stringify(data)),
                lastUpdateTime: ""
            },
            dataType: 'json',
            type: 'post',
            success: function (result) {
                //如果不是手动保存，则不需要进行提示
                //不提示保存成功
                var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
                analyseStatus.addMainData(id, result.data);
                Eventbus.trigger("mining_board_save.mine", id);
            },
            error: function (response) {
                var message = TempoUtils.locale("mine.saveFailed");
                if (response.getResponseHeader("Merit-Session-Expired") == "true") {
                    message = TempoUtils.locale("mine.sessionTimeout");
                }
                $("<div/>").alert({
                    msg: message,
                    title: document.title
                });
            },
            complete: function () {
                if (pro) {
                    Mask.hide(pro);
                }
            }
        });

        if (!analyseId) {
            $.ajax({
                url: contextPath + '/api/ai/flowoperatelog/saveFlowEditOperateLog',
                data: {
                    flowId: id,
                },
                dataType: 'json',
                type: 'post',
                success: function () {
                },
                error: function (response) {
                },
                complete: function () {
                }
            });
        }
        if (!isRunAfter) {
            var minecachedata = window["minecachedata"] || {};
            if (!$.isEmptyObject(minecachedata)) {
                var curFlowCacheInfo = minecachedata[id] || {};
                if (!$.isEmptyObject(curFlowCacheInfo)) {
                    $.ajax({
                        url: contextPath + "/api/ai/mine/deleteMineCache",
                        method: 'post',
                        traditional: true,
                        data: {
                            flowCacheInfo: JSON.stringify(curFlowCacheInfo)
                        },
                        success: function (result) {
                            // 如果缓存删除成功，则清除window中的数据，避免下次再次进行删除操作
                            delete minecachedata[id];
                        },
                        error: function () {
                        }
                    });
                }
            }
        }
    }

    /**
     * 刷新日志
     */
    var mineRefresh = function () {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var id = analyseStatus.getMainId();
        var page = analyseStatus.getFlowPanel(id);
        //调用flowpanel的日志请求方法，刷新时立即调用
        page.panel.flowpanel("refreshLog");
    }

    /**
     * 运行当前流程
     */
    var mineRun = function () {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var id = analyseStatus.getMainId();
        var page = analyseStatus.getFlowPanel(id);
        if (!page.panel.flowpanel('isReady')) {
            $("<div/>").alert({
                msg: TempoUtils.locale("mine.taskRunningError"),
                title: TempoUtils.locale("mine.runtask")
            });
            return;
        }
        var board = page.panel.flowpanel('getBoard');
        // 调用此方法在流程执行之前触发各个节点的validateNode函数，校验各个节点状态
        page.panel.flowpanel('getLastNodeStatus');
        page.panel.flowpanel('updateNodeStatus', '');
        var json = board.miningboard("getFlowData");
        //子流程提交执行，目前有问题，会提交多余节点，影响执行和洞察节点显示
        //var json = page.panel.flowpanel('getRootData').flow;
        //判断注释框的个数
        var numcoms = 0;
        if (json != null) {
            for (var i = 0; i < json.children.length; i++) {
                var node = json.children[i];
                if (node._widgetName == 'minecommentnode') {
                    numcoms++;
                }
            }
        }
        if (json == null || json.children == null || json.children.length - numcoms == 0) {
            if (json == null) {
                $("<div/>").alert({
                    msg: TempoUtils.locale("mine.nodePropError"),
                    title: TempoUtils.locale("mine.runtask")
                });
                return;
            } else {
                $("<div/>").alert({
                    msg: TempoUtils.locale("mine.liuchenglianjieend"),
                    title: TempoUtils.locale("mine.runtask")
                });
                return;
            }
        } else {
            var insightControlInfos = {
                allInsightIsOpen: false,
                dataInsightIsOpen: true,
                graphInsightIsOpen: true,
                nodeInsightIsOpen: false,
                signalDataInsightIsOpen: true,
            }
            var insightControlInfo = {};
            if (json.insightControlInfo == undefined) {
                insightControlInfo = insightControlInfos;
            } else {
                var insightTarget = $('#insight-setting-more-menu');
                var allInsightIsOpen = insightTarget.find("#allSelectBtn").is(":checked");
                var dataInsightIsOpen = insightTarget.find("#dataCollection").is(":checked");
                var nodeInsightIsOpen = insightTarget.find("#nodeInsight").is(":checked");
                var graphInsightIsOpen = insightTarget.find("#graphInsight").is(":checked");
                var signalDataInsightIsOpen = insightTarget.find("#signalData").is(":checked");
                insightControlInfo.allInsightIsOpen = allInsightIsOpen;
                insightControlInfo.dataInsightIsOpen = dataInsightIsOpen;
                insightControlInfo.nodeInsightIsOpen = nodeInsightIsOpen;
                insightControlInfo.graphInsightIsOpen = graphInsightIsOpen;
                insightControlInfo.signalDataInsightIsOpen = signalDataInsightIsOpen;
            }
            json.insightControlInfo = insightControlInfo;
            var children = json.children;
            for (var i = 0; i < children.length; i++) {
                var childNode = children[i];
                var eid = childNode.eid;
                var tt = $('#' + eid);
                if (tt.length > 0) {
                    tt[tt.attr('_widgetname')]('deleteCache');
                }
            }
            //文件输出多输出端口增加前端校验
            try {
                if (!writefileNodeRunValidate(board, children)) {
                    return;
                }
            } catch (e) {
            }
        }
        subprocessDel(json);
        subprocessLastNodeIsOpenCache(json);
        //  如果流程以及类子流程中包含python编程节点，如果其参与计算，则将其上次你保存的数据库元信息清空
        TempoMineUtils.cleanScriptNodeOutPortMetaOfJson(json);
        //清除流程日志
        page.panel.flowpanel('clearFlowLog');
        var pro = Mask.create({text: TempoUtils.locale("mine.taskIsRunning")});
        $.ajax({
            url: contextPath + "/api/ai/mine/excuteFlow",
            data: {
                flow: TempoMineUtils.encodeParams(JSON.stringify(json)),
                flowId: id,
                analyseId: window[constant.ANALYSE_ID]
            },
            type: 'post',
            success: function (result) {
                //执行成功之后才把停止按钮的stop的class去掉
                page.panel.find('.tempo-mine-stop').removeClass('manual-stop');
                page.panel.flowpanel('showFlowLog', result.message);
                if (result.status) {
                    // 清空各个节点的执行状态
                    page.panel.flowpanel('updateNodeStatus', '');
                    page.panel.flowpanel('startStatusTimer', result.exid,
                        result.mineServiceInfo);
                }
                mineSave(null, null, true);
                $.ajax({
                    url: contextPath + '/api/ai/flowoperatelog/saveFlowExcuteOperateLog',
                    data: {
                        flowId: id,
                    },
                    dataType: 'json',
                    type: 'post',
                    success: function () {
                    },
                    error: function (response) {
                    },
                    complete: function () {
                    }
                });
            },
            error: function (response) {
                var message = TempoUtils.locale("mine.runtaskError");
                if (response.getResponseHeader("Merit-Session-Expired") == "true") {
                    message = TempoUtils.locale("mine.sessionTimeout");
                }
                $("<div/>").alert({
                    msg: message,
                    title: document.title
                });
            },
            complete: function () {
                Mask.hide(pro);
            }
        })
    }

    /**
     * 文件输出多输出端口增加前端校验
     * @param board 当前面板
     * @param children 当前面板数据
     * @returns {boolean} 是否可以执行 false为不可执行
     */
    var writefileNodeRunValidate = function (board, children) {
        var instance = board[board.attr('_widgetname')]('getJspInstance');
        var allConns = instance.getAllConnections();
        for (var i = 0; i < children.length; i++) {
            //节点数据
            var childNode = children[i];
            //节点eid
            var eid = childNode.eid;
            //节点id
            var nodeType = childNode.nodeType;
            //输入端口的数据
            var getInScopes = childNode.scope.inScope;
            //兼容历史流程，文件输出节点为一个输入端口的为历史流程，不进行校验
            if ((nodeType == "writefile" && getInScopes.length != 1) || nodeType == "writefilebatch") {
                //节点对应的名称，用于提示
                var name = childNode.alias;
                //拿到文件输出的输出端口
                var outScopes = childNode.scope.outScope;
                //拿到文件输出的输出端口个数
                var outScopeNums = outScopes.length;
                var connNums = 0;
                for (var j in allConns) {
                    var lconn = allConns[j];
                    //如果有这个属性，说明是子流程里的
                    if (lconn.from_op && lconn.to_op) {
                        if (lconn.from_op == eid && lconn.to_op == "END") {
                            connNums++;
                        }
                    } else {
                        if (lconn.getUuids()[0].split("_")[0] == eid && lconn.getUuids()[1].split("_")[0] == "END") {
                            connNums++;
                        }
                    }
                }
                if (connNums != outScopeNums) {
                    $("<div/>").alert({
                        msg: name + TempoUtils.locale("mine.out_scope_no_all_conn_wall"),
                        title: TempoUtils.locale("mine.runtask")
                    });
                    return false;
                }
            } else if (nodeType == "subprocess" || nodeType == "loopsampledata") {
                //节点对应的名称，用于提示
                var name = childNode.alias;
                //子流程和循环行里也需要判断文件输出节点是否全部连接墙
                var flowReadyData = childNode.flowReadyData;
                if (flowReadyData) {
                    var subChildren = flowReadyData.children;
                    var subConnections = flowReadyData.connections;
                    if (subChildren && subConnections) {
                        for (var j = 0; j < subChildren.length; j++) {
                            //节点数据
                            var subChildNode = subChildren[j];
                            //节点eid
                            var subEid = subChildNode.eid;
                            //节点对应的名称，用于提示
                            var subName = subChildNode.alias;
                            //节点id
                            var subNodeType = subChildNode.nodeType;
                            //输入端口的数据
                            var subGetInScopes = subChildNode.scope.inScope;
                            //兼容历史流程，文件输出节点为一个输入端口的为历史流程，不进行校验
                            if ((subNodeType == "writefile" && subGetInScopes.length != 1) || subNodeType == "writefilebatch") {
                                //拿到文件输出的输出端口
                                var subOutScopes = subChildNode.scope.outScope;
                                //拿到文件输出的输出端口个数
                                var subOutScopeNums = subOutScopes.length;
                                var subConnNums = 0;
                                for (var j in subConnections) {
                                    var lconn = subConnections[j];
                                    //如果有这个属性，说明是子流程里的
                                    if (lconn.from_op && lconn.to_op) {
                                        if (lconn.from_op == subEid && lconn.to_op == "END") {
                                            subConnNums++;
                                        }
                                    }
                                }
                                if (subConnNums != subOutScopeNums) {
                                    $("<div/>").alert({
                                        msg: name + "内" + subName + TempoUtils.locale("mine.out_scope_no_all_conn_wall"),
                                        title: TempoUtils.locale("mine.runtask")
                                    });
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     *  flowreadyData使得子流程可以避过不通到end端口的线路的节点 [process包含了所有的节点，流程提交时暂时转移到tempoSubFullInfo中]
     * 子流程可以嵌套多次---》所以递归剔除,并补加end端点
     */
    var subprocessDel = function (data) {
        var likeSubprocessNodes = ["minesubprocessnode", "mineloopnode"];
        data.children.forEach(function (v, i) {
            if (likeSubprocessNodes.indexOf(v._widgetName) > -1) {
                console.log("subprocessDel");
                v.tempoSubFullInfo = [];
                v.tempoSubFullInfo.push(v.process.flow.children);
                v.tempoSubFullInfo.push(v.process.flow.connections);
                if (!v.flowReadyData || !v.flowReadyData.connections || !v.flowReadyData.children) {
                    return;
                }
                v.process.flow.connections = v.flowReadyData.connections;
                var tempEnd = null;
                v.process.flow.children.forEach(function (value, index) {
                    if (value.eid == 'END' && value.nodeType == 'END') {
                        tempEnd = value;
                    }
                });
                v.process.flow.children = v.flowReadyData.children;
                if (tempEnd) {
                    v.process.flow.children.push(tempEnd);
                }
                subprocessDel(v.process.flow);
            }
        });
    }

    var getNodeData = function (children, eid) {
        for (var i = 0; i < children.length; i++) {
            var curNodeData = children[i];
            var curEid = curNodeData.eid;
            if (curEid == eid) {
                return curNodeData;
            }
        }
    }

    var subprocessLastNodeIsOpenCache = function (json) {
        var children = json.children;
        if (children && children.length > 0) {
            for (var i = 0; i < children.length; i++) {
                var child = children[i];
                if (child.flowReadyData && child.process && child.process.flow) {
                    var flowReadyData = child.process.flow;
                    //var connections = flowReadyData.connections;
                    var innerChildren = flowReadyData.children;
                    //将类子流程中的所有节点都置成需要执行状态
                    for (var k = 0; k < innerChildren.length; k++) {
                        var kparameters = innerChildren[k].parameters;
                        if (kparameters) {
                            kparameters.cachestatus = window.constant.CLOSECACHE;
                            kparameters.isNeedExcute = true;
                        }
                    }
                    // var lastNodeIds = [];
                    // for (var k=0; k < connections.length; k++) {
                    // 	var conn = connections[k];
                    // 	var to_op = conn.to_op;
                    // 	if (to_op == "END") {
                    // 		var lastNodeEid = conn.from_op;
                    // 		if ($.inArray(lastNodeEid, lastNodeIds) == -1) {
                    // 			lastNodeIds.push(lastNodeEid);
                    // 		}
                    // 	}
                    // }
                    // var isOpenCache = false;
                    // for (var j = 0; j < lastNodeIds.length; j++) {
                    // 	var lastNodeId = lastNodeIds[j];
                    // 	var lastNodeData = getNodeData(innerChildren, lastNodeId);
                    // 	if (lastNodeData) {
                    // 		var lastNodeParamters = lastNodeData.parameters;
                    // 		if (lastNodeParamters && lastNodeParamters.cachestatus != window.constant.CLOSECACHE) {
                    // 			isOpenCache = true;
                    // 			break;
                    // 		}
                    // 	}
                    // }
                    // if (isOpenCache) {
                    // 	if (child && child.parameters) {
                    // 		child.parameters.subprocessNeedCache = true;
                    // 	}
                    // } else {
                    // 	if (child && child.parameters) {
                    child.parameters.subprocessNeedCache = false;
                    // 	}
                    // }
                }
            }
        }
    }
    /**
     * 流程执行完后，将转移到tempoSubFullInfo中存储的节点信息再迁回process中
     * 控制子流程执行完后，本主题下的所有节点[包括黄色/未连接到end端口的节点]的正常显示
     * 子流程可以嵌套多次---》所以递归添加
     */
    var subprocessAdd = function (data) {
        var likeSubprocessNodes = ["minesubprocessnode", "mineloopnode"];
        data.flow.children.forEach(function (v, i) {
            if (likeSubprocessNodes.indexOf(v._widgetName) > -1 && v.tempoSubFullInfo != undefined) {
                console.log("subprocessAdd");
                v.process.flow.children = v.tempoSubFullInfo[0];
                v.process.flow.connections = v.tempoSubFullInfo[1];
                subprocessAdd(v.process);
            }
        });
    }
    /**
     * 带缓存运行当前流程
     */
    var mineRunCache = function () {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var id = analyseStatus.getMainId();
        var page = analyseStatus.getFlowPanel(id);
        if (!page.panel.flowpanel('isReady')) {
            $("<div/>").alert({
                msg: TempoUtils.locale("mine.taskRunningError"),
                title: TempoUtils.locale("mine.runtask")
            });
            return;
        }
        var board = page.panel.flowpanel('getBoard');
        page.panel.flowpanel('getLastNodeStatus');

        var json = null;
        json = board.miningboard("getFlowData");
        var numcoms = 0;
        if (json != null) {
            for (var i = 0; i < json.children.length; i++) {
                var node = json.children[i];
                if (node._widgetName == 'minecommentnode') {
                    numcoms++;
                }
            }
            var insightControlInfos = {
                allInsightIsOpen: false,
                dataInsightIsOpen: true,
                graphInsightIsOpen: true,
                nodeInsightIsOpen: false,
                signalDataInsightIsOpen: true,
            }
            var insightControlInfo = {};
            if (json.insightControlInfo == undefined) {
                insightControlInfo = insightControlInfos;
            } else {
                var insightTarget = $('#insight-setting-more-menu');
                var allInsightIsOpen = insightTarget.find("#allSelectBtn").is(":checked");
                var dataInsightIsOpen = insightTarget.find("#dataCollection").is(":checked");
                var nodeInsightIsOpen = insightTarget.find("#nodeInsight").is(":checked");
                var graphInsightIsOpen = insightTarget.find("#graphInsight").is(":checked");
                var signalDataInsightIsOpen = insightTarget.find("#signalData").is(":checked");
                insightControlInfo.allInsightIsOpen = allInsightIsOpen;
                insightControlInfo.dataInsightIsOpen = dataInsightIsOpen;
                insightControlInfo.nodeInsightIsOpen = nodeInsightIsOpen;
                insightControlInfo.graphInsightIsOpen = graphInsightIsOpen;
                insightControlInfo.signalDataInsightIsOpen = signalDataInsightIsOpen;
            }
            json.insightControlInfo = insightControlInfo;
        }

        //子流程提交执行，目前有问题，会提交多余节点，影响执行和洞察节点显示
        if (json == null || json.children == null || json.children.length - numcoms == 0) {
            if (json == null) {
                $("<div/>").alert({
                    msg: TempoUtils.locale("mine.nodePropError"),
                    title: TempoUtils.locale("mine.runtask")
                });
                return;
            } else {
                $("<div/>").alert({
                    msg: TempoUtils.locale("mine.processconnectend"),
                    title: TempoUtils.locale("mine.runtask")
                });
                return;
            }
        }
        board.miningboard("setExcuteStatus", json.children, json.connections);
        var children = json.children;
        //文件输出多输出端口增加前端校验
        try {
            if (!writefileNodeRunValidate(board, children)) {
                return;
            }
        } catch (e) {
        }
        for (var i = 0; i < children.length; i++) {
            var childNode = children[i];
            var flowReadyData = childNode.flowReadyData;
            if (!$.isEmptyObject(flowReadyData)) {
                if (likeSubprocessNodess.indexOf(childNode.nodeType) > -1) {
                    board.miningboard("setExcuteStatus", flowReadyData.children, flowReadyData.connections);
                } else {
                    childNode.parameters.isNeedExcute = false;
                    var subprocessChildren = flowReadyData.children;
                    if (subprocessChildren && subprocessChildren.length && subprocessChildren.length > 0) {
                        for (var j = 0; j < subprocessChildren.length; j++) {
                            var subprocessChildNode = subprocessChildren[j];
                            var subprocessParameters = subprocessChildNode.parameters;
                            if (!$.isEmptyObject(subprocessParameters)) {
                                subprocessParameters.isNeedExcute = false;
                                subprocessParameters.excuteFlowType = "startNodeExcute";
                            }
                        }
                    }
                }
            }
        }
        //  如果流程以及类子流程中包含python编程节点，如果其参与计算，则将其上次你保存的数据库元信息清空
        TempoMineUtils.cleanScriptNodeOutPortMetaOfJson(json);
        page.panel.flowpanel('updateNodeStatus', '');
        page.panel.flowpanel('clearFlowLog');
        // 从缓存出执行时删除未连接end的节点
        subprocessDel(json);
        var pro = Mask.create({text: TempoUtils.locale("mine.taskIsRunning")});
        $.ajax({
            url: contextPath + "/api/ai/mine/startNodeExcuteFlow",
            data: {
                flow: TempoMineUtils.encodeParams(JSON.stringify(json)),
                flowId: id,
                analyseId: window[constant.ANALYSE_ID]
            },
            type: 'post',
            success: function (result) {
                page.panel.flowpanel('showFlowLog', result.message);
                if (result.status) {
                    // 清空各个节点的执行状态
                    //page.panel.flowpanel('updateNodeStatus', '');
                    page.panel.flowpanel('startStatusTimer', result.exid,
                        result.mineServiceInfo);
                }
                mineSave(null, null, true);
            },
            error: function (response) {
                var message = TempoUtils.locale("mine.runtaskError");
                if (response.getResponseHeader("Merit-Session-Expired") == "true") {
                    message = TempoUtils.locale("mine.sessionTimeout");
                }
                $("<div/>").alert({
                    msg: message,
                    title: document.title
                });
            },
            complete: function () {
                Mask.hide(pro);
            }
        });

        $.ajax({
            url: contextPath + '/api/ai/flowoperatelog/saveFlowExcuteOperateLog',
            data: {
                flowId: id,
            },
            dataType: 'json',
            type: 'post',
            success: function () {
            },
            error: function (response) {
            },
            complete: function () {
            }
        });
    }

    /**
     * 终止当前正在运行的流程
     */
    var mineStop = function () {
        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
        var id = analyseStatus.getMainId();
        var page = analyseStatus.getFlowPanel(id);
        var option = page.panel.flowpanel('getJson');
        page.panel.find('.tempo-mine-stop').addClass('button-disabled manual-stop');
        var mineServiceInfo = option.mineServiceInfo;
        var exId = option.exid;
        var masterType = option.flow.runTimeConfig.masterType;
        var data = {
            exId: exId ? exId : null,
            mineServiceInfo: JSON.stringify(mineServiceInfo ? mineServiceInfo : null),
            masterType: masterType,
            flowId: option.id
        };
        var prog = Mask.create();
        $.ajax({
            url: contextPath + "/api/ai/mine/stopFlow",
            data: data,
            type: 'post',
            success: function (result) {
                //page.panel.flowpanel('updateFlowStatus', constant.FLOW_STATUS.KILLED)
                console.log("任务终止命令发送成功");
                page.panel.flowpanel("refreshLog");
            },
            complete: function () {
                if (prog) {
                    Mask.hide(prog);
                }
            }
        })

        $.ajax({
            url: contextPath + '/api/ai/flowoperatelog/saveFlowStopOperateLog',
            data: {
                flowId: id,
            },
            dataType: 'json',
            type: 'post',
            success: function () {
            },
            error: function (response) {
            },
            complete: function () {
            }
        });
    }

    /**
     * 保存指定流程
     */
    var saveAnalyseFlow = function (analyseId, isRun) {
        mineSave(null, analyseId, isRun);
    }

    /**
     * 遮罩管理
     * */
    var Mask = (function () {
        var map = {};
        return {
            create: function (param) {
                param = param || {};
                var p = $("<div/>").tempoprogressbar(param).uniqueId();
                var id = p.attr('id');
                map[id] = new Date().getTime();
                return p;
            },
            hide: function (pro) {
                if (pro) {
                    var id = pro.attr('id');
                    var t = map[id];
                    delete map[id];
                    var e = new Date().getTime();
                    var delay = e - t < 300 ? 300 : 1;
                    setTimeout(function () {
                        pro.tempoprogressbar("close");
                    }, delay);
                }
            }
        }
    })();
}

$(function () {
    var toolbar = new MineToolbar();
    toolbar.init();
    setTimeout(function () {
        var fn = arguments.callee;
        if (typeof MineModelingController != "undefined") {
            new MineModelingController();
        } else {
            setTimeout(fn, 1000);
        }
    }, 10);

});